import 'dart:convert';

import 'package:eplorex/models/message/chat_message_type.dart' as types;

import '../dao/userinfo_dao.dart';
import 'local_shared_cache.dart';

class UserSession {
  static final Map<num, types.User> _localCacheUser = {};

  static UserSession instance = UserSession();

  Future<types.User?> getUser(num uid) async {
    types.User? user = _localCacheUser[uid];
    if (user == null) {
      // load from local cache
      // LocalSharedCache.removeString(uid.toString());
      String? userInfoStr = await LocalSharedCache.getString(uid.toString());
      if (userInfoStr != null) {
        user = types.User.fromJson(jsonDecode(userInfoStr));
      } else {
        // load from remote server
        user = await UserInfoDao.fetch(uid);
      }

      if (user != null) {
        _localCacheUser[uid] = user!;
        LocalSharedCache.saveString(uid.toString(), jsonEncode(user));
      }
    }
    return user;
  }
}
